<!--
 * @Author: xiaxia
 * @Description: 
 * @Date: 2024-06-24 16:38:12
 * @LastEditTime: 2024-07-01 09:12:32
 * @FilePath: \project\src\views\product\attr\index.vue
-->
<template>
  <div>
    <!-- 分类 -->
    <Category :isTable="isTable"/>
    <!-- 属性 -->
    <el-card style="margin: 10px 0;">
      <!-- 当前属性列表 -->
      <div v-show="isTable==0">
        <el-button 
          icon="plus" 
          type="primary" 
          @click="hAdd"
          :disabled="!categoryStore.category3Id"
        >添加属性</el-button>
        <el-table :data="attrData" border style="margin: 10px 0;">
          <el-table-column label="序号" width="100" type="index"/>
          <el-table-column prop="attrName" label="属性名称"/>
          <el-table-column prop="attrValueList" label="属性值名称">
            <template #="{row}">
              <el-tag v-for="item in row.attrValueList" :key="item.id" style="margin: 0 5px;">{{ item.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column  label="操作" width="120">
            <template #="{row}">
              <el-button icon="edit" size="small" @click="hEdit(row)"></el-button>
              <el-popconfirm
                width="220"
                confirm-button-text="确认"
                cancel-button-text="取消"
                icon="InfoFilled"
                :title="`确认删除${row.attrName}这个属性吗?`"
                @confirm="hDelete(row.id)"
              >
                <template #reference>
                  <el-button icon="delete" size="small"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加|修改属性 -->
      <div v-show="isTable==1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input v-model="attrParams.attrName" placeholder="请输入属性名称" clearable />
          </el-form-item>
        </el-form>
        <el-button 
          icon="plus" 
          type="primary" 
          @click="hAddValue"
          :disabled="!attrParams.attrName"
        >添加属性</el-button>
        <el-button @click="cancel">取消</el-button>

        <el-table :data="attrParams.attrValueList" border style="margin: 10px 0;">
          <el-table-column label="序号" width="100" type="index"/>
          <el-table-column prop="valueName" label="属性值">
            <template #="{row,$index}">
              <el-input 
                v-if="row.flag"
                :ref="(vc:any)=>inputArr[$index]=vc"
                @blur="toLook(row, $index)" 
                placeholder="请输入属性值" 
                v-model="row.valueName"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{row.valueName}}</div>
            </template>
          </el-table-column>
          <el-table-column  label="操作" width="120">
            <template #="{row,index}">
              <el-popconfirm
                width="220"
                confirm-button-text="确认"
                cancel-button-text="取消"
                icon="InfoFilled"
                :title="`确认删除${row.valueName}这个属性值吗?`"
                @confirm="attrParams.attrValueList.splice(index,1)"
              >
                <template #reference>
                  <el-button icon="delete" size="small"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        
        <el-button type="primary" @click="hSaveValue" :disabled="!(attrParams.attrValueList.length>0)">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup name="Attr">
import {ref, watch, reactive, nextTick, onBeforeUnmount} from 'vue';
import useCategoryStore from '@/store/modules/category.ts'
import {reqAttrList, reqAddEditTrademark, reqDeletAttr} from '@/api/product/attr'
import { AttrListResponse, Attrs, Attr, AttrValue } from "@/api/product/attr/type"
import { ElMessage } from 'element-plus';

const categoryStore = useCategoryStore() // 存在store的category
let attrData = ref<Attrs>([]) // 表格
let isTable = ref<number>(0) // 0:展示表格 1:添加|编辑操作
let isEdit = ref<boolean>(false) // false:添加 true:编辑
let attrParams = reactive<Attr>({
  attrName: '', // 属性名称
  attrValueList: [], // 属性值
  categoryId: '', // 三级分类id
  categoryLevel: 3, // 属性级别为三
})
let inputArr = ref<any>([])

// 获取属性列表
const getList = async () => {
  const {category1Id, category2Id, category3Id} = categoryStore // 从store获取分类id
  const res:AttrListResponse = await reqAttrList(category1Id, category2Id, category3Id)
  if(res.code != 200) return
  attrData.value = res.data
}

watch(() => categoryStore.category3Id, async ()=>{
  attrData.value = []
  if(!categoryStore.category3Id) return
  getList()
})

// 新增属性
const hAdd = ()=> {
  Object.assign(attrParams, {
    attrName: '', // 属性名称
    attrValueList: [], // 属性值
    categoryId: categoryStore.category3Id, // 三级分类id
    categoryLevel: 3, // 属性级别为三
  })
  isTable.value = 1
  isEdit.value = false
}
// 编辑属性
const hEdit = (row:Attr)=> {
  isTable.value = 1
  isEdit.value = true
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
// 删除属性
const hDelete = async (id:number|string)=> {
  const res:any = await reqDeletAttr(id)
  if(res.code!=200) return ElMessage({type:'error',message: '删除失败'+res.message})
  ElMessage({type:'success',message: '删除成功！'})
  getList()
}

// 关闭 - 编辑或者新增
const cancel = ()=>{
  isTable.value = 0
}
// 新增属性值
const hAddValue = ()=>{
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, // false:属性值展示框 true:属性值输入框
  })
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length-1].focus()
  });
}
// 保存属性
const hSaveValue = async ()=> {
  const res:any = await reqAddEditTrademark(attrParams)
  if(res.code !=200) return ElMessage({type:'error',message: '添加失败！'+res.message})
  ElMessage({
    type:'success',
    message: isEdit?'修改成功！':'添加成功'
  })
  isTable.value = 0
  getList()
}
// 属性值input --> 属性值div
const toLook = (row:AttrValue, $index:number)=>{
  //  非法情况 1  
  if(row.valueName.trim()=='') {
    attrParams.attrValueList.splice($index,1)
    return ElMessage({type:'error',message: '属性值不能为空！'})
  }
  // 非法情况 2
  let a = attrParams.attrValueList.find(item => {
    if(item!=row) return item.valueName == row.valueName
  })
  if(a){ 
    attrParams.attrValueList.splice($index,1)
    return ElMessage({type:'error',message: '属性值不能重复！'})
  }
  row.flag = !row.flag
}
// 属性值div --> 属性值input
const toEdit = (row:AttrValue, $index:number)=>{
  row.flag = !row.flag
  nextTick(() => {
    inputArr.value[$index].focus()
  });
}

// 组件销毁 清空仓库数据
onBeforeUnmount(()=>{
  categoryStore.$reset()
})
</script>

<style lang="scss" scoped>

</style>